package com.bsoft.gol.hbs.bbpmessagel.channel;

import com.bsoft.gol.hbs.bbpmessagel.enums.MsgTypeEnum;
import com.bsoft.gol.hbs.bbpmessagel.enums.WhetherEnum;
import com.bsoft.gol.hbs.bbpmessagel.template.WxMpTemplateData;
import com.bsoft.gol.hbs.bbpmessagel.template.WxMpTemplateMessage;
import com.bsoft.gol.hbs.bbpmessagel.util.Constants;
import com.bsoft.gol.hbs.bbpmessagel.util.WeChatMessageApiUtil;
import com.alibaba.fastjson.JSONObject;
import ctd.message.Message;
import ctd.net.rpc.json.JSONResponseBean;
import com.bsoft.gol.hbs.dao.HiSysMsgTplDao;
import hcn.base.message.HiSysMsgTplEntity;
import hcn.util.ResultCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import ssdev.bbp.message.channel.MessageChannel;

import java.lang.reflect.Array;
import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * @description:微信公众号
 * @author: zhengcb10708
 * @create: 2022-03-11 17:01
 **/
public class WeChatSendMsgService implements MessageChannel {
    @Value("${mini_app_id}")
    private String weChatMiniAppId;
    @Autowired
    private HiSysMsgTplDao hiSysMsgTplDao;
    @Override
    public JSONResponseBean sendMessage(String openId, Message message) {
        JSONResponseBean baseResponse= new JSONResponseBean();
        Map<String, String> extras = message.getExtras();
        //accessToken 微信公众号token
        if(!isEmpty(extras)&&!isEmpty(extras.get("openId"))&&!isEmpty(extras.get("accessToken"))){
            //处理微信公众号消息模板配置
            handleWechatTemplate(extras);
            //如果jsonString为空，则会直接把根据消息模板得到的文本消息内容直接发送给用户
            JSONObject parameters = new JSONObject();
            parameters.put("touser", extras.get("openId"));
            parameters.put("msgtype", "text");
            JSONObject textSub = new JSONObject();
            textSub.put("content", message.getContent());
            parameters.put("text", textSub);
            JSONObject jsonObject=null;
            if(isEmpty(extras.get("wechatJsonString"))){
                jsonObject=parameters;
            }else {
                jsonObject = JSONObject.parseObject(extras.get("wechatJsonString"));
            }
            return doSend(extras.get("accessToken"),jsonObject,true);
        }else {
            baseResponse.setCode(ResultCode.ERROR);
            baseResponse.setMsg("微信公众号入参不全");
            return baseResponse;
        }
    }

    private JSONResponseBean doSend(String access_token, JSONObject jsonObject, boolean retry) {
        JSONResponseBean baseResponse;
        if (jsonObject.containsKey("template_id")) {
            //存在模板id字段即为发送模板消息
            baseResponse = WeChatMessageApiUtil.sendTemplateMessage(jsonObject.toJSONString(),
                    access_token);
        } else {
            //缺少模板id字段即默认为发送文本消息
            baseResponse = WeChatMessageApiUtil.sendtextMessageToUser(jsonObject.toJSONString(), access_token);
        }
        if (ResultCode.SUCCESS != baseResponse.getCode() && retry) {
            return doSend(access_token, jsonObject, false);
        } else {
            return baseResponse;
        }
    }

    //处理微信公众号消息模板配置
    private void handleWechatTemplate(Map<String, String> extras){
       if(extras.containsKey("cd")&&!isEmpty(extras.get("cd"))&&!isEmpty(extras.get("openId"))){
           List<HiSysMsgTplEntity> hiSysMsgTplEntityList=hiSysMsgTplDao.findHiSysMsgTplListByParams(MsgTypeEnum.WECHAT_OFFICIAL_ACCOUNT_TEMP_MSG.getCode(),extras.get("cd"));
           if(!isEmpty(hiSysMsgTplEntityList)){

               WxMpTemplateMessage templateMessage =
                       WxMpTemplateMessage.builder().toUser(extras.get("openId"))
                               .templateId(getHiSysMsgTplValue(hiSysMsgTplEntityList, Constants.SUBSCRIPTIONTEMPLATEID))
                               .url(handleConfigureVariable(getHiSysMsgTplValue(hiSysMsgTplEntityList, Constants.SUBSCRIPTIONJUMPURL),extras)).build();
               if (WhetherEnum.YES.getKey().equals(getHiSysMsgTplValue(hiSysMsgTplEntityList,Constants.SUBSCRIPTIONJUMPMINIFLAG))) {
                   //需要跳转小程序的参数
                   WxMpTemplateMessage.MiniProgram miniProgram =
                           new WxMpTemplateMessage.MiniProgram();
                   miniProgram.setAppid(weChatMiniAppId);
                   if (StringUtils.hasText(getHiSysMsgTplValue(hiSysMsgTplEntityList,Constants.APPLETSTEMPLATEJUMPPAGE))) {
                       miniProgram.setPagepath(handleConfigureVariable(getHiSysMsgTplValue(hiSysMsgTplEntityList,Constants.APPLETSTEMPLATEJUMPPAGE),
                               extras));
                   }
                   templateMessage.setMiniProgram(miniProgram);
               }
               //根据数据库配置进行组装公众号模板
               for(HiSysMsgTplEntity hiSysMsgTplItem:hiSysMsgTplEntityList){
                   templateMessage.addData(new WxMpTemplateData(hiSysMsgTplItem.getTplKey(),
                           handleConfigureVariable(hiSysMsgTplItem.getTplVal()==null?"":hiSysMsgTplItem.getTplVal(),
                                   extras), hiSysMsgTplItem.getColor()));
               }
               extras.put("wechatJsonString",templateMessage.toJson());
           }
       }
    }

    /**
     * @Describe: 处理配置里面的变量信息
     * @Param: [configureKeyword, extra]
     * @Return: java.lang.String
     * @Author: zhengcb10708
     * @Date: 2022/3/13 15:02
     */
    private String handleConfigureVariable(String configureKeyword, Map<String,String> extra) {
        //遍历消息体变量列表，进行变量赋值
        if (!isEmpty(extra) && StringUtils.hasText(configureKeyword)) {
            for (Map.Entry<String, String> entry : extra.entrySet()) {
                //这里处理变量只处理##【】包裹的，避免出现非变量文本被替换
                String msgVariableKey = entry.getKey();
                if (msgVariableKey != null
                        && ((msgVariableKey.startsWith("#") && msgVariableKey.endsWith("#")) || (msgVariableKey.startsWith("【") && msgVariableKey.endsWith("】")))) {
                    configureKeyword = configureKeyword.replaceAll(msgVariableKey,
                            entry.getValue() == null ? "" :
                                    entry.getValue());

                }
            }
        }
        return configureKeyword;
    }
    //获取微信公众号模板维护指定的值
    private String getHiSysMsgTplValue(List<HiSysMsgTplEntity> hiSysMsgTplEntityList,String hiSysMsgTpKeyWord){
         if(!isEmpty(hiSysMsgTplEntityList)){
            for(HiSysMsgTplEntity hiSysMsgTplEntity:hiSysMsgTplEntityList){
                if(hiSysMsgTplEntity.getTplKey().equals(hiSysMsgTpKeyWord)){
                    return hiSysMsgTplEntity.getTplVal();
                }
            }
         }
         return null;
    }
    //校验空值
    private static boolean isEmpty(Object obj) {
        if (obj == null) {
            return true;
        }
        if (obj instanceof CharSequence) {
            return ((CharSequence) obj).length() == 0;
        }
        if (obj instanceof Collection) {
            return ((Collection<?>) obj).isEmpty();
        }
        if (obj instanceof Map) {
            return ((Map<?, ?>) obj).isEmpty();
        }
        if (obj.getClass().isArray()) {
            return Array.getLength(obj) == 0;
        }
        return false;
    }
}
